package cn.tedu.blackhorse.security;

import cn.tedu.blackhorse.mapper.AdminMapper;
import cn.tedu.blackhorse.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security自动调用loadUserByUsername()方法获取用户名为【{}】的用户详情……", s);

        AdminLoginInfoVO loginInfo = adminMapper.getLoginInfoByUsername(s);
        if (loginInfo == null) {
            String message = "登录失败,用户名不存在";
            log.warn(message);
            throw new BadCredentialsException(message);
        }
        String[] split = loginInfo.getName().split(",");
        List<String> strings = Arrays.asList(split);
        /*List<String> permissions = null;*/
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : strings) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        log.info("从数据库中获取用户信息={}", loginInfo);
        AdminDetails adminDetails = new AdminDetails(
                loginInfo.getUsername(),new BCryptPasswordEncoder().encode(loginInfo.getPassword()),
                loginInfo.getEnable()==1,authorities
        );
        adminDetails.setId(loginInfo.getId());
        log.debug("11111111111111111111111111111111111111111111111:{}",adminDetails.getId());
        /*UserDetails userDetails = User.builder()
                .username(loginInfo.getUsername())//给UserDetails的username赋值
                .password(loginInfo.getPassword())//给UserDetails的password赋值
                .accountExpired(false)// 账号是否已过期
                .accountLocked(false)// 账号是否已锁定
                .credentialsExpired(false)// 凭证是否已过期
                .disabled(loginInfo.getEnable() == 0)// 账号是否已禁用
                .authorities(loginInfo.getPermissions().toArray(new String[] {}))// 权限，【注意】必须调用此方法表示此用户具有哪些权限
                .build();*/
        log.debug("即将向Java security框架返回值UserDetails对象:{}", adminDetails);
        return adminDetails;
    }




}
